<template>
  <ArkDialog v-model:options="options">
    <slot>
      <div class="px-4 py-4">
        <ArkForm ref="form" v-model:options="options.form">
          <template v-for="(slot, slotName) in $slots" #[slotName]="slotProps">
            <slot :name="slotName" v-bind="slotProps"/>
          </template>
        </ArkForm>
      </div>
    </slot>
  </ArkDialog>
</template>

<script setup lang="ts">
import {onBeforeMount, onMounted, type PropType, useTemplateRef,} from "vue";
import _ from "lodash";
import ArkDialog from "../../common/ark-dialog/ArkDialog.vue";
import ArkForm from "../../common/ark-form/ArkForm.vue";
import {FormItem, Interaction} from "../../common/ark-form/ArkFormOptions";
import ArkDialogFormOptionsDefault, {ArkDialogFormExpose, ArkDialogFormOptions} from "./ArkDialogFormOptions";
import {ArkActionButton} from "../../common-type/ark-action-button";

/** 接口（组件的接口）。包括：defineOptions、defineModel、defineProps、defineEmits、defineExpose、defineSlots */
const options = defineModel("options", {
  type: Object as PropType<ArkDialogFormOptions>,
  default: () => ArkDialogFormOptionsDefault
});

defineExpose<ArkDialogFormExpose>({
  validate() {
    return formRef.value.validate();
  },
  reset() {
    return formRef.value.reset();
  },
  fetchOptions(formItem, formItems) {
    return formRef.value?.fetchOptions(formItem, formItems);
  },
});

/** 本地状态 (本地的响应式 property)。包括：ref、computed */
const formRef = useTemplateRef("form");

/** 事件（通过响应式事件触发的回调）。包括：watch */

/** 生命周期钩子（按照它们被调用的顺序）。包括：onBeforeMount、onMounted、onBeforeUpdate、onUpdated、onBeforeUnmount、onUnmounted */
onBeforeMount(() => {
  init();
});

onMounted(() => {
});

/** 非响应式的 property (不依赖响应系统的实例 property)。包括：常规函数 */
const init = () => {
  _.defaultsDeep(options.value, ArkDialogFormOptionsDefault);

  if (_.isNil(options.value.footer)) {
    options.value.footer = {}
  }

  if (_.isNil(options.value.footer.confirm?.beforeClick)) {
    const actionButtonDefault: Partial<ArkActionButton> = {
      beforeClick() {
        return formRef.value.validate();
      },
    };

    _.defaultsDeep(options.value.footer?.confirm, actionButtonDefault)
  }

  if (_.isNil(options.value.footer.cancel?.afterClick)) {
    const actionButtonDefault: Partial<ArkActionButton<any>> = {
      afterClick() {
        options.value.show = false;
      },
    };

    _.defaultsDeep(options.value.footer?.cancel, actionButtonDefault)
  }

  if (options.value.form?.layout?.column === 1 && _.isNil(options.value.width)) {
    options.value.width = 500;

    _.forOwn(options.value.form?.formItems, (formItem: FormItem) => {
      const interactionDefault: Partial<Interaction> = {
        width: "95%",
      };

      if (_.isNil(formItem.interaction)) {
        formItem.interaction = {}
      }

      if (_.isNil(formItem.interaction.width)) {
        _.defaultsDeep(formItem.interaction, interactionDefault,);
      }
    });
  }
};

/** 其它 */
</script>

<style scoped></style>
